package com.movitech.mobile.cz.base.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.util.UserUtils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.util.ListObjCopyUtil;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.config.AttachmentSubTypeEnum;
import com.movitech.mobile.cz.base.modules.config.AttachmentTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.modules.vo.PageRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.bizvo.BannerListResponseVO;
import com.movitech.mobile.cz.base.sys.bizvo.BannerRequestVO;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.entity.SBanner;
import com.movitech.mobile.cz.base.sys.entity.ext.ExtSBanner;
import com.movitech.mobile.cz.base.sys.mapper.SBannerMapper;
import com.movitech.mobile.cz.base.sys.mapper.ext.ExtSBannerMapper;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.movitech.mobile.cz.base.sys.service.SBannerService;

/**
 * <p>
 * banner维护 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sBannerService")
@Transactional
public class SBannerServiceImpl extends ServiceImpl<SBannerMapper, SBanner> implements SBannerService {

	private final static Logger logger = Logger.getLogger(SBannerServiceImpl.class);

	@Autowired
	private SAttachmentService sAttachmentService;
	@Autowired
	private ExtSBannerMapper extSBannerMapper;

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
	@Override
	public RestReturnResult<Object> saveOrUpdateBanner(BannerRequestVO bannerRequestVO) throws RuntimeException{
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		LicenseUtil.INSTANCE.validate();
		try{
			SBanner banner = null;
			if(bannerRequestVO != null){

				if(StringUtils.isNotEmpty(bannerRequestVO.getId())){ //update

					banner = baseMapper.selectById(bannerRequestVO.getId());
					if(banner != null){

						banner.setBannerName(bannerRequestVO.getBannerName());
						banner.setBannerType(bannerRequestVO.getBannerType());
						banner.setBannerSort(bannerRequestVO.getBannerSort());

						Date updateDate = new Date();
						String userId = UserUtils.getCurrentUserId();
						banner.setUpdateBy(userId);
						banner.setUpdateDate(updateDate);
						banner.setDelFlag(CommonConstants.NO_INTEGER);

						baseMapper.updateById(banner);

						//上传图片
						sAttachmentService.deleteBatch(banner.getId(), AttachmentTypeEnum.ATTACHMENT_TYPE_34.getCode(),
								AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_2.getCode());

						List<AttachmentVO> lstAttachments = bannerRequestVO.getLstAttachments();
						this.saveBannerPics(lstAttachments, banner.getId());


						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[1], CommonConstants.SUCCESS_DESCS[1]);

					}else{ //数据不存在
						hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
					}

				}else{ //insert

					banner = new SBanner();
					banner.setId(IdGenUtils.uuid());
					banner.setBannerName(bannerRequestVO.getBannerName());
					banner.setBannerType(bannerRequestVO.getBannerType());
					banner.setBannerSort(bannerRequestVO.getBannerSort());

					Date createDate = new Date();
					String userId = UserUtils.getCurrentUserId();
					banner.setBannerStatus(CommonConstants.YES_INTEGER);
					banner.setCreateBy(userId);
					banner.setCreateDate(createDate);
					banner.setUpdateBy(userId);
					banner.setUpdateDate(createDate);
					banner.setDelFlag(CommonConstants.NO_INTEGER);

					baseMapper.insert(banner);

					//上传图片
					List<AttachmentVO> lstAttachments = bannerRequestVO.getLstAttachments();
					this.saveBannerPics(lstAttachments, banner.getId());

					hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[0], CommonConstants.SUCCESS_DESCS[0]);
				}

			}else{//请求数据出错
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("=============saveOrUpdateBanner===============e:====" + e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}


		return hResult;
	}

	private boolean saveBannerPics(List<AttachmentVO> lstAttachments, String bannerId) throws Exception{

		boolean flag = false;

		if(lstAttachments != null && lstAttachments.size() > 0){
			List<SAttachment>  attachments = ListObjCopyUtil.copyTo(lstAttachments, SAttachment.class);

			for(SAttachment sa : attachments){
				sa.setRelatedId(bannerId);
				sa.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_34.getCode());
				sa.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_2.getCode());
				sa.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
			}

			if(attachments != null && attachments.size() > 0){
				flag = sAttachmentService.insertBatch(attachments);
			}

		}

		return flag;

	}

	@Override
	public RestReturnResult<Object> updateBannerForDel(String id) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		if(StringUtils.isNotEmpty(id)){

			SBanner banner = baseMapper.selectById(id);
			if(banner != null){
				banner.setDelFlag(CommonConstants.YES_INTEGER);

				Date updateDate = new Date();
				String userId = UserUtils.getCurrentUserId();
				banner.setUpdateBy(userId);
				banner.setUpdateDate(updateDate);

				baseMapper.updateById(banner);

				hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[2], CommonConstants.SUCCESS_DESCS[2]);

			}else{ //数据不存在
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
			}

		}else{
			hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
		}

		return hResult;
	}

	@Override
	public RestReturnResult<Object> updateBannerStatus(BannerRequestVO bannerRequestVO) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		if(bannerRequestVO != null){

			if(StringUtils.isNotEmpty(bannerRequestVO.getId())){

				SBanner banner = baseMapper.selectById(bannerRequestVO.getId());

				if(banner != null){
					banner.setBannerStatus(bannerRequestVO.getBannerStatus());

					Date updateDate = new Date();
					String userId = UserUtils.getCurrentUserId();
					banner.setUpdateBy(userId);
					banner.setUpdateDate(updateDate);

					baseMapper.updateById(banner);

					if(CommonConstants.YES_INTEGER == bannerRequestVO.getBannerStatus()){//启用
						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[3], CommonConstants.SUCCESS_DESCS[3]);
					}else{//停用
						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[4], CommonConstants.SUCCESS_DESCS[4]);
					}

				}else{//数据不存在
					hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
				}

			}else{
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
			}

		}else{//请求数据出错
			hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
		}

		return hResult;
	}

	@Override
	public RestReturnResult<Object> getBannerList(PageRequestVO pageRequestVO) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL);

		try{

			PageCode pageCode = new PageCode(pageRequestVO.getPageNumber(), pageRequestVO.getPageSize());

			Map<String, Object> map = new HashMap<String, Object>();
			pageCode.setCount(extSBannerMapper.getBannerListCounts(map));

			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("isPage", pageRequestVO.getPageFlag());

            List<ExtSBanner> ls = extSBannerMapper.getBannerList(map);
            if(ls != null && ls.size() > 0){
            	List<BannerListResponseVO> result = ListObjCopyUtil.copyTo(ls, BannerListResponseVO.class);

            	EntityWrapper wrapper = new EntityWrapper();
            	SAttachment param = new SAttachment();
            	for(BannerListResponseVO vo : result){
            		param.setRelatedId(vo.getId());
            		param.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_34.getCode());
            		param.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_2.getCode());
            		param.setDelFlag(CommonConstants.NO_INTEGER);
            		wrapper.setEntity(param);
            		List<SAttachment> attachments = sAttachmentService.selectList(wrapper);
            		List<AttachmentVO> lstAttachments = ListObjCopyUtil.copyTo(attachments, AttachmentVO.class);

            		vo.setLstAttachments(lstAttachments);
            	}

            	pageCode.setList(result);
            }else{
            	pageCode.setList(null);
            }

            hResult = new RestReturnResult(CommonConstants.SUCCESS, pageCode);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("============getBannerList=============e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}

		return hResult;
	}

}
